programming4us
           
 
 
Programming

Programming Excel with VBA and .NET : Tasks in Visual Basic - Find Truth & Compare Bits

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
9/7/2011 11:31:55 AM

1. Find Truth

If statements and Do loops rely on Boolean expressions to control what they do. Those Boolean expressions are usually shown as a condition placeholder in the statement's syntax:

    If condition Then ...

and:

    Do While condition ...

A Boolean expression is simply an item that Visual Basic can determine to be either True or False. Mostly those expressions are very obvious. The fragment If str = "" Then says "if the variable str is an empty string, then execute the following lines of code." In this case, the equal sign (=) works as a comparison operator, not an assignment operator. Visual Basic can use the operator both ways because it understands that the context of an If statement is different from the standalone statement:

    str = ""

That line performs an assignment, not a comparison! This type of dual use is called overloading . If you hear someone say "operators are overloaded in Visual Basic," they are just stating that = can be used two different ways.

There's something else you need to know about Boolean expressions, though. In Visual Basic, any nonzero value is considered to be True. I know that's weird, but it's important because it means the following two fragments are equivalent:

    If str = "" Then ...

If Len(str) Then ...

The second form literally says "if the length of str, then..." which doesn't make any sense unless you know that 0 equals False and any other value equals True. This second form used to be a common optimization technique because Visual Basic returns the length of a string very quickly. These types of optimizations are less popular today, because the clarity of code is now considered more important than saving a few processor cycles.

Table 1 lists the Visual Basic operators that are used to perform comparisons that result in Boolean expressions.

Table 1. Visual Basic comparison operators
OperatorComparisonOperatorComparison
=Equal to<>Not equal to
<Less than>Greater than
<=Less than or equal to>=Greater than or equal to
LikePattern match (strings)IsExact match (objects)

Expressions can also be combined to form compound Boolean expressions using the operators listed in Table 2.

Table 2. Visual Basic Boolean operators truth table
exp1Operatorexp2= Result
TrueAndTrueTrue
TrueOrFalseTrue
FalseOrTrueTrue
NotFalseTrue
TrueEqvTrueTrue
FalseEqvFalseTrue
TrueImpTrueTrue
FalseImpTrueTrue
FalseImpFalseTrue
TrueXORFalseTrue
FalseXORTrueTrue

The most-used Boolean operators are And, Or, and Not.

2. Compare Bits

Computers use binary numbers internally. That's because they don't have 10 fingers to count on; they have only 2: on and off, which represent 1 and 0, respectively. Knowing that helps you understand another use for the operators in Table 2—Boolean operators can also be used in mathematical operations to change the individual bits that make up a number, as illustrated by the following code:

    Sub ToBorNotToB( )
Dim b As Byte
b = 93
Debug.Print b, Not b, b Or Not b
' Displays: 93 162 255
End Sub

In the preceding code, Not and Or have a mathematical effect on b. Specifically, Not returns the bits that are 0 (255 - b) and Or combines the bits in b and Not b (93 + 162). These are called bitwise operations and they make more sense if you look at b as a binary number (Figure 1).

Bitwise operations are used to determine if a number contains one or more bit flags . Bit flags are numeric constants that can be combined in a single number without interfering with each other, as shown in Figure 2.

Figure 2 illustrates that the result of the VarType function can contain both the vbArray flag and any of the other type flags. For instance, vbArray And vbVariantOr operator: indicates an array of variants. You can test if a variable contains an array of variants by combining the type flags with the

Figure 1. Evaluating bitwise operations

Figure 2. VbVarType constants are bit flags

    Sub TestArrayType( )
Dim arr, vt As VbVarType
arr = Array(1, 2, 3, 4, 5)
vt = VarType(arr)
If vt And (vbArray Or vbVariant) Then _
MsgBox "Variable arr is an array of variants."
End Sub

If the bit pattern of vt and vbArray Or vbVariant match, the expression is True and the message is displayed. That kind of test is sometimes called a bit mask . Bit masking is also used to extract parts of a variable. For instance, the Excel Color property returns a Long integer value that contains three byte values indicating the red, green, and blue components of the color as shown by the following code:

    Sub ShowColors( )
Dim i As Integer, rng As Range, rgb As Long
Set rng = Range("ColorTable")
For i = 1 To 56
rng.Offset(i, 0).Interior.ColorIndex = i
rgb = rng.Offset(i, 0).Interior.Color
rng.Offset(i, 1).Value = rgb And &HFF
rng.Offset(i, 2).Value = rgb \ &H100 And &HFF
rng.Offset(i, 3).Value = rgb \ &H10000 And &HFF
Next
End Sub

The expression rgb And &HFF returns any of the bits in the first byte of rgb that are 1. The subsequent expressions use integer division to shift to the next byte, getting the second and third bytes from rgb, which are then masked. It often helps to see the bits in a variable when working with bitwise operators, so I wrote the following functions to convert numbers into strings that represent the bit values:

    Function ByteToBin(byt As Byte) As String
Dim i As Integer, bin As String
For i = 0 To 7
If byt And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
ByteToBin = bin
End Function

Function IntToBin(itg As Integer) As String
Dim i As Integer, bin As String
For i = 0 To 15
If itg And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
IntToBin = bin
End Function

Function LngToBin(lng As Long) As String
Dim i As Integer, bin As String
' Note that this omits 2 ^ 31 because of overflow.
For i = 0 To 30
If lng And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
LngToBin = bin
End Function
Other -----------------
- Programming WCF Services : Queued Services - Delivery Failures (part 2) - Processing the Dead-Letter Queue
- Programming WCF Services : Queued Services - Delivery Failures (part 1) - Configuring the Dead-Letter Queue
- Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Cancellation
- Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Sort Examples
- jQuery 1.3 : DOM Manipulation - Wrapping elements & Copying elements
- iOS SDK : Debugging (part 4) - Instruments—Leaks
- iOS SDK : Debugging (part 3) - NSZombieEnabled
- iOS SDK : Debugging (part 2) - Watchpoints
- iOS SDK : Debugging (part1 )
- iOS SDK : Installing Applications on an iPhone
- Software Testing with Visual Studio Team System 2008 : Web Testing - Recording a test
- Software Testing with Visual Studio Team System 2008 : Unit testing web services & Code coverage unit test
- .NET Debugging : Introduction to the Tools - SOS & SOSEX
- .NET Debugging : CLR 4.0 - Synchronization & Interoperability
- iPhone Programming : Connecting to the Network - Getting Data from the Internet
- iPhone Programming : Connecting to the Network - Sending Email
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Check Results
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Read and Write Files
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Get Dates and Times
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Work with Text
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us